<?php

class xRequest {

    private static $source = false;
    private static $xml = false;
    private static $simulated_params = false;
    private static $query_string;

    static function params() {
	if (self::$simulated_params !== false) {
	    return self::$simulated_params;
	}
	if(!self::$xml) return @self::$source['param'];
	else return (string) self::$xml->xpath("//param");
    }

    static function init () {
	if (self::$source != 0) return;

	// trying to load request code from POST
	$rq = $_POST+$_GET;
	self::$source = @$rq['query'];
	if (!self::$source) {
	    if (count($rq) > 0) {
		self::$source['id'] = @$rq['query_id'];
		self::$source['type'] = (@$rq['query_type']) ? $rq['query_type'] : 'HTML';
		self::$source['param'] = $rq;
		return true;
	    } else {
		parse_str($_SERVER['QUERY_STRING'], $params);
		if (key_exists('query_type', $params)) {
		    self::$source['id'] = $params['query_id'];
		    self::$source['type'] = (@$params['query_type']) ? $parans['query_type'] : 'HTML';
		    self::$source['param'] = array_merge($params, $rq);
		}
	    }
	    self::$source['id'] = 0;
	    self::$source['type'] = 'HTML';
	    self::$source['param'] = array();
	}

	if (!is_array(self::$source)) self::$xml = simplexml_load_string(self::$source);
    }

    static function id() {
	if (self::$simulated_params !== false) {
	    return self::$simulated_params['id'];
	}
	if(!self::$xml) return self::$source['id'];
	else return self::$xml['id'];
    }

    static function type() {
	if (self::$simulated_params != false) {
	    return self::$simulated_params['type'];
	}
	if(!self::$xml) return strtoupper(self::$source['type']);
	else return strtoupper(self::$xml->type);
    }

    static function param($name) {
	if (self::$simulated_params !== false) {
	    return addslashes(self::$simulated_params[$name]);
	}
	if(!self::$xml) return addslashes(@self::$source['param'][$name]);
	else return (string) addslashes(self::$xml->xpath("//param[@name='$name']"));
    }


    static function simulate($params) {
	Log::put('Simulation started...');
	if (self::$simulated_params !== false) {
	    Log::fatal('Unable to start Request simulation: already started.', QConst::X_SIMULATION_FAILED);
	}
	self::$simulated_params = $params;
    }

    function simulating() {
	return (false || !self::$simulated_params);
    }

    function unsimulate() {
	self::$simulated_params = false;
    }
}

xRequest::init();
?>